/**
 * 权限工具
 * @author luguoxiang
 * @date 2021-09-07
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
import { KeyEnum } from '../enums/Constant';
import { storage } from './storage';
import { cache } from './cache';
import { serverUrl } from '@/config';

const { ACCESS_TOKEN, REFRESH_TOKEN } = KeyEnum;

/**
 * 登录
 * @param res
 */
export function signin(res: { accessToken: string; refreshToken: string }): void {
    cache.put(ACCESS_TOKEN, res.accessToken, 60);
    storage.put(ACCESS_TOKEN, res.accessToken, new Date(Number(res.accessToken.split('.')[1])));
    storage.put(REFRESH_TOKEN, res.refreshToken, new Date(Number(res.refreshToken.split('.')[1])));
}

/**
 * 登出
 */
export function signout(): void {
    storage.remove(ACCESS_TOKEN);
    storage.remove(REFRESH_TOKEN);
    cache.remove(ACCESS_TOKEN);
}

/**
 * 获取token
 * @returns {string}
 */
// eslint-disable-next-line consistent-return
export function getToken(): string | undefined {
    return cache.compute(ACCESS_TOKEN, () => storage.get(ACCESS_TOKEN), 60);
}

/**
 * 获取刷新token
 * @returns {*|void}
 */
export function getRefreshToken(): string {
    return storage.get(REFRESH_TOKEN);
}

/**
 * 加载token
 * @return
 */
export function loadToken() {
    return new Promise<string>((resolve, reject) => {
        const token = getToken();
        if (token) {
            return resolve(token);
        }
        const refreshToken = getRefreshToken();
        if (refreshToken) {
            uni.request({
                url: `${serverUrl}/system/login/refreshToken?refreshToken=${refreshToken}`,
            })
                .then((res: any) => {
                    if (200 <= res.statusCode && res.statusCode < 300) {
                        res = res.data.data;
                        signin(res);
                        resolve(res.accessToken);
                    } else {
                        const err = new Error(res?.data?.msg);
                        err.response = res;
                        signout();
                        reject(err);
                    }
                })
                .catch((err: any) => {
                    signout();
                    reject(err);
                });
        } else {
            reject();
        }
    })
}